<template>
  <div>
    <el-upload
      class="upload-demo"
      ref="upload"
      multiple
      drag
      action="#"
      :on-change="handleChange"
      :before-upload="beforeUpload"
      :on-remove="handleRemove"
      :http-request="customUpload"
      :limit="maxNumber"
      :auto-upload="false"
    >
      <div class="el-upload__text">
        <svg class="icon" style="width: 40px; height: 40px">
          <use xlink:href="#icon-shangchuan"/>
        </svg>
        <div>拖拽上传 / 点击上传</div>
      </div>
      <div slot="tip" class="el-upload__tip">
        一次最多上传{{ maxNumber }}个文件，且每个文件不超过{{ maxSize }}M！
      </div>
    </el-upload>

    <div style="text-align: center; margin-top: 20px">
      <el-button type="success" style="font-size: 12px" @click="submitUpload">
        上传
      </el-button>
    </div>
  </div>
</template>

<script>
export default {
  props: {
    maxSize: {
      type: Number,
      default: 5,
    },
    maxNumber: {
      type: Number,
      default: 5,
    },
  },

  data() {
    return {};
  },

  computed: {},

  watch: {},

  created() {
  },

  mounted() {
  },

  methods: {
    submitUpload() {
      this.$refs.upload.submit();
    },
    customUpload(options) {
      let form = new FormData();
      form.append("file", options.file);
      const loading = this.$loading({
        lock: true,
        text: "封面上传中...",
        spinner: "el-icon-loading",
      });
      this.$createHttp.uploadFile(form).then((res) => {
        loading.close()
        if (res.code === 200) {
          this.$emit("addPicture", res.data);
          this.$message({
            message: "上传成功!",
            type: "success",
          });
        } else {
          this.$message({
            message: "上传失败，请重试",
            type: "error",
          });
        }
      });
    },
    // 上传文件之前的钩子，参数为上传的文件，若返回 false 或者返回 Promise 且被 reject，则停止上传
    beforeUpload(file) {
    },
    // 文件列表移除文件时的钩子
    handleRemove(file, fileList) {
    },
    // 添加文件、上传成功和上传失败时都会被调用
    handleChange(file, fileList) {
      let flag = false;

      if (file.size > this.maxSize * 1024 * 1024) {
        this.$message({
          message: "图片最大为" + this.maxSize + "M！",
          type: "warning",
        });
        flag = true;
      }

      if (flag) {
        fileList.splice(fileList.size - 1, 1);
      }
    },
  },
};
</script>

<style scoped>
</style>
